package com.citsin.atlas.fragment

import android.content.Context
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.citsin.atlas.R
import com.citsin.atlas.adapter.MediaListAdapter
import com.citsin.atlas.viewmodel.MediaViewModel
import com.citsin.atlas.viewmodel.MediaViewModelProviderFactory
import com.citsin.atlas.widget.DividerItemDecoration
import kotlinx.android.synthetic.main.fragment_media_list.recyclerView

/**
 * citsin
 * 2019-06-04
 */
class MediaListFragment : Fragment() {


    private lateinit var mAdapter:MediaListAdapter
    private lateinit var mViewModel:MediaViewModel
    override fun onAttach(context: Context) {
        super.onAttach(context)
        mAdapter= MediaListAdapter(context)

        val types = arguments!!.getIntArray("types").toTypedArray()
        val id = arguments!!.getString("id")
        val factory = MediaViewModelProviderFactory(requireActivity().application,types,id)
        mViewModel  = ViewModelProvider(this,factory).get(MediaViewModel::class.java)
        mViewModel.getMedia().observe(this, Observer { medias->
            mAdapter.submitList(medias)
        })
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_media_list, container, false)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView.layoutManager = StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL)
        recyclerView.addItemDecoration(DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL))
        recyclerView.addItemDecoration(DividerItemDecoration(requireContext(), DividerItemDecoration.HORIZONTAL))
        recyclerView.adapter = mAdapter
        mAdapter.setOnItemClickListener { i, media ->
            val bundle = arguments
            bundle?.putInt("pos", i)
            Navigation.findNavController(view).navigate(R.id.action_media_to_preview, bundle)
        }


    }
}
